<template>
  <div class="pane-content">
    <a-form layout="vertical">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-card
            title="已选中房源"
            :bodyStyle="{
              height: isCostContract ? '230px' : '450px',
            }"
          >
            <template #extra>
              <a-button
                type="link"
                @click="checkedHouseShow = !checkedHouseShow"
              >
                {{ checkedHouseShow ? "选择房源" : "查看已选" }}
              </a-button>
            </template>
            <CheckedHousingResources
              :areaInput="true"
              :checkable="!checkedHouseShow"
              :houseList="content.checkedHouse"
              :allHouseList="allHouseList"
              :checkControl="true"
              :clauseType="
                content.attribute == 'property' ? 'property' : 'lease'
              "
              :includeSelfArea="includeSelfArea"
              :maxTotal="isCostContract"
              :areaInputDisabled="paymentByRooms"
              @getResult="handleCheckHouseChange"
              @request="$utils.commonRequest"
            />
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card>
            <a-row :gutter="12" :wrap="true" class="w-100p">
              <a-col :span="8">
                <a-form-item label="租赁面积" v-bind="validateInfos.lease_area">
                  <a-input-group compact>
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="formData.lease_area"
                      style="width: 120px"
                      :min="0"
                      disabled
                      :precision="4"
                    />
                    <span class="num-input-suffix">{{ areaUnit.name }}</span>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-if="isCostContract">
                <a-form-item v-bind="validateInfos.lease_mode">
                  <template #label>
                    <span style="margin-right: 6px;">计租方式</span>
                    <a-tooltip>
                      <template #title >
                        <div>固定租金：按合同中条款自动生成固定金额的付款账单</div>
                        <div>托管计租：楼宇的租客在结清租金/物业费账单时会给原业主进行分成，自动生成付款账单</div>
                      </template >
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </template>
                  <a-select
                    v-model:value="formData.lease_mode"
                    placeholder="请选择"
                    @change="handleCostLeaseChange"
                  >
                    <a-select-option
                      v-for="item of lease_mode_List"
                      :value="item.key"
                      :key="item.key"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card
            :title="content.bond_type_txt"
            class="mt-20"
            v-if="content.use_bond"
          >
            <a-row :gutter="12" :wrap="true" class="w-100p">
              <a-col :span="8">
                <a-form-item
                  label="保证金类型"
                  v-bind="validateInfos['bond_clause.bond_type']"
                >
                  <a-select
                    v-model:value="formData.bond_clause.bond_type"
                    placeholder="请选择"
                    :disabled="bondTypeDisabled"
                  >
                    <a-select-option
                      v-for="item of optionData.bondType"
                      :value="item.key"
                      :key="item.key"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="保证金金额"
                  v-bind="validateInfos['bond_clause.bond_price']"
                >
                  <a-input-group compact>
                    <a-input-number
                      style="width: 60%"
                      placeholder="请输入"
                      v-model:value="formData.bond_clause.bond_price"
                      :min="0"
                    />
                    <a-select
                      style="width: 40%"
                      v-model:value="formData.bond_clause.bond_unit"
                      :disabled="bondUnitDisabled || isHostedCost"
                    >
                      <a-select-option
                        v-for="item of optionData.bond_unit"
                        :value="item.key"
                        :key="item.key"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  label="币种（单位）"
                  v-bind="validateInfos['bond_clause.currencyUnit']"
                >
                  <a-select
                    v-model:value="formData.bond_clause.currencyUnit"
                    placeholder="请选择"
                    :disabled="true"
                  >
                    <a-select-option
                      v-for="item of optionData.currencyUnit"
                      :value="item.key"
                      :key="item.key"
                    >
                      {{ item.name + "(" + item.key + ")" }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
          <a-card
            :title="content.cost_type_name + '含税'"
            class="mt-20"
            v-if="
              (content.use_lease && !isCostContract) ||
              (content.useLease == 1 && content.useBond == 1) ||
              content.useBond == 0 ||
              content.useLease == 1
            "
          >
            <a-row :gutter="12" :wrap="true" class="w-100p">
              <a-col :span="8">
                <a-form-item v-bind="validateInfos['tax_clause.taxRule']">
                  <template #label>
                    <span style="margin-right: 6px;">含税规则</span>
                    <a-tooltip>
                      <template #title >当选择单价含税时，则默认条款的合同单价即为含税价</template >
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </template>
                  <a-select
                    v-model:value="formData.tax_clause.taxRule"
                    placeholder="请选择"
                    @select="handleTaxRuleChange"
                    :disabled="rateDisabled"
                  >
                    <a-select-option
                      v-for="item of optionData.taxRule"
                      :value="item.key"
                      :key="item.key"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item v-bind="validateInfos['tax_clause.taxRate']">
                  <template #label>
                    <span style="margin-right: 6px;">税率</span>
                    <a-tooltip>
                      <template #title >当没有时,请联系管理人员添加对应的发票模板</template >
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </template>
                  <a-select
                    v-if="taxRatelist.length > 0"
                    v-model:value="formData.tax_clause.taxRate_id"
                    style="width: calc(100% - 25px)"
                    @change="changetaxRate"
                    :options="taxRatelist"
                  >
                  </a-select>
                  <a-input
                    v-else
                    style="width: 80px;"
                    v-model:value="formData.tax_clause.taxRate"
                  />
                  <span class="num-input-suffix">%</span>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
      <a-row class="mt-20" v-for="(item, index) of clauseList" :key="item.key">
        <a-col :span="24">
          <normal-clause
            :title="content.cost_type_txt"
            :type="content.attribute"
            :trigger="trigger"
            :paneFrom="content.key"
            :index="index"
            :content="item"
            :clauseContent="content"
            @remove="handleClauseListRemove"
            @success="handleValidateSuccess"
            @fail="handleValidateFail"
            @change="handleClauseChange"
            :isHostedCost="isHostedCost"
            :canAddNormalClause="canAddNormalClause"
            @add="handleClauseAdd"
            @dataChange="(data) => draftDataChange(data, item, 'multiple_clause')"
          />
        </a-col>
      </a-row>
      <a-row class="btn-row" @click="addNormalClause" v-if="canAddNormalClause">
        <a-button type="link">
          <template #icon>
            <PlusOutlined />
          </template>
          {{ content.name }}
        </a-button>
      </a-row>
      <a-row
        class="mt-20"
        v-for="(item, index) of incrClauseList"
        :key="item.key"
      >
        <a-col :span="24">
          <increase-clause
            :index="index"
            :paneFrom="content.key"
            :trigger="trigger"
            :content="item"
            @remove="handleClauseListRemove"
            @success="handleValidateSuccess"
            @fail="handleValidateFail"
            :canAddIncreaseClause="canAddIncreaseClause"
            @add="handleClauseAdd"
            @dataChange="(data) => draftDataChange(data, item, 'increment_clause')"
          />
        </a-col>
      </a-row>
      <a-row
        class="btn-row"
        @click="addIncreaseClause"
        v-if="canAddIncreaseClause"
      >
        <a-button type="link">
          <template #icon>
            <PlusOutlined />
          </template>
          递增条款
        </a-button>
      </a-row>
      <a-row
        class="mt-20"
        v-for="(item, index) of discountClauseList"
        :key="item.key"
      >
        <a-col :span="24">
          <discount-clause
            :index="index"
            :paneFrom="content.key"
            :trigger="trigger"
            :content="item"
            @remove="handleClauseListRemove"
            @success="handleValidateSuccess"
            @fail="handleValidateFail"
            :canAddDiscountClause="canAddDiscountClause"
            @add="handleClauseAdd"
            @dataChange="(data) => draftDataChange(data, item, 'discount_clause')"
          />
        </a-col>
      </a-row>
      <a-row
        class="btn-row"
        @click="addDiscountClause"
        v-if="canAddDiscountClause"
      >
        <a-button type="link">
          <template #icon>
            <PlusOutlined />
          </template>
          优惠条款
        </a-button>
      </a-row>
      <a-row class="mt-20">
        <a-col :span="24">
          <a-card title="备注条款" size="small">
            <a-textarea
              placeholder="请输入备注内容"
              v-model:value="formData.remark_clause"
              :auto-size="{ minRows: 4 }"
            />
          </a-card>
        </a-col>
      </a-row>
      <a-row class="btn-row detail" @click="getLeaseDetail">
        <a-button type="link" size="large" :loading="genLoading">
          <template #icon>
            <PlusOutlined />
          </template>
          {{ isPurposeContract ? "预览账单明细" : "生成账单明细" }}
        </a-button>
      </a-row>
      <rent-detail
        :detail="leaseDetail"
        :params="detailParams"
        :type="submitType"
        :paneFrom="content.key"
        :trigger="trigger"
        @success="handleValidateSuccess"
        @fail="handleValidateFail"
      />
    </a-form>

  </div>
</template>

<script>
import moment from "moment";
import {
  computed,
  defineComponent,
  reactive,
  ref,
  watch,
  toRefs,
  toRaw,
  nextTick,
} from "vue";
import NormalClause from "./NormalClause.vue";
import IncreaseClause from "./IncreaseClause.vue";
import DiscountClause from "./DiscountClause.vue";
import RentDetail from "./RentDetail.vue";
import {PlusOutlined, QuestionCircleOutlined} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import { TextTip, CheckedHousingResources } from "bl-common-vue3";
import { useRoute } from "vue-router";
import _ from "lodash";

const useForm = Form.useForm;

export default defineComponent({
  name: "ContractFeeClause",
  components: {
    QuestionCircleOutlined,
    CheckedHousingResources,
    NormalClause,
    IncreaseClause,
    DiscountClause,
    RentDetail,
    PlusOutlined,
    TextTip,
  },
  props: {
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
    contentTrigger: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const paneFrom = computed(() => ({
      id: props.content.id,
      key: props.content.key,
    }));

    const $route = useRoute();
    // 是否成本合同
    const isCostContract = computed(
      () => $route.query.contractType == "costContract"
    );

    // 是否变更合同
    const isChangeContract = computed(
      () => $route.query.contractEditType == "change"
    );

    // 是否意向变更合同
    const isPurposeChangeContract = computed(
      () => $route.query.contractType == "purposeContractChange"
    );

    const includeSelfArea = computed(
      () => isRenewal.value || isChangeContract.value || isPurposeChangeContract.value
    );

    const canAddNormalClause = computed(
      () => props.content.use_lease && !isCostContract.value
    );

    const canAddIncreaseClause = computed(
      () => props.content.use_incr == 1 && !isCostContract.value
    );

    const canAddDiscountClause = computed(
      () => props.content.use_discount == 1 && !isCostContract.value
    );

    // 租金明细
    const leaseDetail = ref({});

    // 正数
    const numberRule = [
      {
        required: true,
        validator: (rules, value) => utils.pNumberValidator(rules, value),
        trigger: "change",
      },
    ];

    // 自然数
    const numberRule2 = [
      {
        required: true,
        validator: (rules, value) => utils.nNumberValidator(rules, value),
        trigger: "change",
      },
    ];

    const requiredRule = [{ required: true, message: "必填" }];
    const unRequiredRule = [{ required: false, message: "必填" }];

    const state = reactive({
      formData: {
        lease_area: 0,
        bond_clause: {
          bond_type: undefined,
          bond_price: "",
          bond_unit: undefined,
          currencyUnit: undefined,
        },
        remark_clause: "",
        tax_clause: {
          taxRule: 1,
          taxRate: undefined,
          taxRate_id: undefined,
        },
        lease_mode: "",
      },
      rulesData: {
        lease_area: numberRule,
        "bond_clause.bond_type": requiredRule,
        "bond_clause.bond_price": numberRule2,
        "bond_clause.bond_unit": requiredRule,
        "bond_clause.currencyUnit": requiredRule,
        "tax_clause.taxRule": isCostContract.value
          ? unRequiredRule
          : requiredRule,
        "tax_clause.taxRate": isCostContract.value
          ? unRequiredRule
          : numberRule2,
        lease_mode: isCostContract.value ? requiredRule : unRequiredRule,
      },
      optionData: {},
      areaUnit: {},
      rateList: [],
      rateDisabled: false,
      lease_mode_List: [], //成本合同计租方式下拉框
      isHostedCost: false, //成本合同计租方式是否托管
      checkedHouseShow: true, // 已选房源展示列表
      houseCheckedIds: [],
      taxRatelist: [],
    });

    // 成本合同计租方式改变
    const handleCostLeaseChange = (value, option) => {
      if (option && option.value == "unit2") {
        state.isHostedCost = true;
        state.formData.bond_clause.bond_unit = "unit_2";
      } else {
        state.isHostedCost = false;
        state.formData.bond_clause.bond_unit = "unit_1";
      }
    };

    const setDraftLocal = (key, data) => {
      if ($route.query.id) return;
      props.content.contentInfo = _.cloneDeep(state.formData);
      props.content.multiple_clause = _.cloneDeep(clauseList.value);
      props.content.increment_clause = _.cloneDeep(incrClauseList.value);
      props.content.discount_clause = _.cloneDeep(discountClauseList.value);
    };

    watch(
      () => state.formData,
      (value) => {
        setClauseChange();
        setDraftLocal();
      },
      { deep: true }
    );

    const setClauseChange = (changed = true) => {
      const lastChangeItem =
        store.getters.clauseContentList[paneFrom.value.key];
      if (lastChangeItem && lastChangeItem.changed == changed) {
        return;
      }
      if (lastChangeItem) {
        store.dispatch("SetClauseTabChange", {
          key: paneFrom.value.key,
          changed: changed,
        });
      }
    };

    const handleAreaChange = (data) => {
      if (props.content.basic_clause && props.content.basic_clause.lease_area) {
        return;
      }
      state.formData.lease_area =
        props.content.attribute == "lease"
          ? data.leaseTotalArea
          : data.proprtyTotalArea;
      state.formData.lease_area = utils.parseNumber(
        state.formData.lease_area,
        4
      );
    };

    const { resetFields, validate, validateInfos } = useForm(
      state.formData,
      state.rulesData
    );

    let params = {
      mainParams: {},
      normalLease: [],
      increaseLease: [],
      discountLease: [],
    };
    const validateForm = () => {
      validate()
        .then(() => {
          let _formData = _.cloneDeep(state.formData);
          if (!props?.content?.use_bond) {
            _formData.bond_clause = null;
          }
          params.mainParams = JSON.parse(JSON.stringify(_formData));
          getParams();
        })
        .catch(() => {
          handleValidateFail({ type: "main" });
        });
    };
    const handleValidateSuccess = (e) => {
      if (isFailed) {
        return;
      }
      const { type, content } = e;
      if (type == "normal") {
        params.normalLease.push(content);
      }
      if (type == "increase") {
        params.increaseLease.push(content);
      }
      if (type == "discount") {
        params.discountLease.push(content);
      }
      if (type == "detail") {
        params.reportDetail = content;
      }
      if (type == "house") {
        params.checkedBuild = content;
      }
      getParams();
    };
    let isFailed = false;
    const handleValidateFail = (e) => {
      if (isFailed) {
        return;
      }
      isFailed = true;
      if (submitType.value == "next") {
        context.emit("fail", { key: props.content.key, msg: e.msg });
        return;
      }
      if (submitType.value == "detail") {
        if (genLoading.value) {
          message.error(e.msg || "请完善表单信息~");
        }
        genLoading.value = false;

        return;
      }
    };

    const detailParams = ref({});
    const getParams = () => {
      if (submitType.value == "detail") {
        getDetailParams();
        return;
      }
      if (submitType.value == "next") {
        getAllParams();
        return;
      }
    };
    // 获取生成明细参数并请求接口
    const getDetailParams = () => {
      if (
        Object.keys(params.mainParams).length &&
        params.normalLease.length == clauseList.value.length &&
        params.increaseLease.length == incrClauseList.value.length &&
        params.discountLease.length == discountClauseList.value.length
      ) {
        // console.log("getParams", params);
        const basicInfo = store.getters.addFormData.basicInfo;
        const { mainParams, normalLease, increaseLease, discountLease } =
          params;
        let tmpNormalLease = [];
        //成本合同 托管计租特殊处理
        if (
          isCostContract.value &&
          state.formData.lease_mode == "unit2" &&
          normalLease.length > 0
        ) {
          tmpNormalLease[0] = {
            cost_type: normalLease[0].cost_type,
            divide_rate: normalLease[0].divide_rate,
            cost_compute_rule: normalLease[0].cost_compute_rule,
            payment_time_unit1: normalLease[0].payment_time_unit1,
            payment_time: normalLease[0].payment_time,
            payment_time_unit2: normalLease[0].payment_time_unit2,
            cost_type_list: normalLease[0].cost_type_list,
            compute_lease_list: normalLease[0].compute_lease_list,
            cost_compute_rule_list: normalLease[0].cost_compute_rule_list,
            charge_begintime: normalLease[0].charge_begintime,
            charge_endtime: normalLease[0].charge_endtime,
          };
        } else {
          tmpNormalLease = normalLease;
        }

        detailParams.value = {
          clause_id: props.content.clause_id,
          lease_area: utils.parseNumber(mainParams.lease_area, 4),
          lease_square: state.areaUnit.key,
          sign_time: basicInfo.sign_time,
          lease_starttime: basicInfo.lease_starttime,
          lease_endtime: basicInfo.lease_endtime,
          unit_price_point: basicInfo.unit_price_point,
          calculate_accuracy: basicInfo.calculate_accuracy,
          calculate_order: basicInfo.calculate_order,
          receivable_round: basicInfo.receivable_round,
          leaseTerms: tmpNormalLease,
          bondTerms: mainParams.bond_clause,
          rentTaxTerms: mainParams.tax_clause,
          incrTerms: increaseLease,
          discountTerms: discountLease,
        };
        // 成本合同特殊传参
        if (isCostContract.value) {
          detailParams.value.lease_mode = state.formData.lease_mode;
        }
        let submitParams = {
          baseTerm: JSON.stringify(detailParams.value),
        };
        // 成本合同特殊传参
        if (isCostContract.value) {
          submitParams.op_type = 4;
        }
        request
          .post("/org", "/contract/reportPays", {
            ...submitParams,
          })
          .then((res) => {
            leaseDetail.value = utils.getClauseDetailByGroup(
              res.data,
              props.content.attribute
            );
            message.success("已生成最新的租金明细表~");
            setClauseChange(false);
          })
          .finally(() => {
            genLoading.value = false;
          });
      }
    };
    // 点击下一步整理参数
    const getAllParams = () => {
      if (!params.checkedBuild.room || !params.checkedBuild.room.length) {
        context.emit("fail", {
          key: props.content.key,
          msg: "请检查房源是否已选择！",
        });
        return;
      }
      if (
        Object.keys(params.mainParams).length &&
        Object.keys(params.checkedBuild).length &&
        params.normalLease.length == clauseList.value.length &&
        params.increaseLease.length == incrClauseList.value.length &&
        params.discountLease.length == discountClauseList.value.length &&
        Object.keys(params.reportDetail).length
      ) {
        let clauseForm = {
          clause_id: props.content.clause_id,
          clause_type: props.content.clause_type,
          attribute: props.content.attribute,
          basic_clause: {
            lease_area: utils.parseNumber(params.mainParams.lease_area, 4),
            lease_square: state.areaUnit.key,
            lease_mode: state.formData.lease_mode,
          },
          bond_clause: params.mainParams.bond_clause,
          tax_clause: params.mainParams.tax_clause,
          remark_clause: params.mainParams.remark_clause,
          multiple_clause: params.normalLease,
          discount_clause: params.discountLease,
          increment_clause: params.increaseLease,
          report_detail: params.reportDetail,
          checked_build: params.checkedBuild,
        };
        context.emit("success", {
          key: props.content.key,
          content: clauseForm,
        });
      }
    };

    // 生成租金明细按钮loading
    const genLoading = ref(false);

    // 生成租金明细
    const trigger = ref(0);
    // detail 生成租金明细 submit 提交下一步
    const submitType = ref("detail");
    const getLeaseDetail = () => {
      submitType.value = "detail";
      genLoading.value = true;
      isFailed = false;
      params = {
        mainParams: {},
        normalLease: [],
        increaseLease: [],
        discountLease: [],
      };
      // 触发表单验证
      trigger.value++;
      validateForm();
      // console.log("getLeaseDetail", trigger.value);
    };

    // 点击下一步触发表单验证
    const handleNextStepClick = () => {
      submitType.value = "next";
      trigger.value++;
      isFailed = false;
      params = {
        mainParams: {},
        checkedBuild: getCheckedBuild(),
        normalLease: [],
        increaseLease: [],
        discountLease: [],
        reportDetail: {},
      };
      validateForm();
    };

    const getCheckedBuild = () => {
      const { content } = props;
      const result = {
        village: {},
        build: [],
        room: [],
      };
      for (let room of content.checkedHouse) {
        if (!room.extra) {
          message.warning("房源信息变更，请返回第一步取消再重新勾选该房源！");
          return;
        }
        const changeHouse = changeHouseList.find((item) => item.id == room.id);
        const inputArea =
          changeHouse && changeHouse.inputArea ? changeHouse.inputArea : {};
        result.room.push({
          id: room.id,
          room_number: room.room_number,
          room_name: room.room_name,
          layer_id: room.extra.layer_id,
          layer_name: room.extra.layer_name,
          inputArea,
          lease_area: inputArea[content.attribute], // 填写的租赁面积
          lease_square: state.areaUnit.key,
          extra: room.extra || {},
          rent_area: room.rent_area,
          rental_area: room.rental_area,
          charging_area: room.charging_area,
        });
        if (!result.village.id) {
          result.village = {
            id: room.extra.village_id,
            name: room.extra.village_name,
            short_name: room.extra.village_short_name,
          };
        }
        const idx = result.build.findIndex(
          (item) => item.id == room.extra.build_id
        );
        if (idx == -1) {
          result.build.push({
            id: room.extra.build_id,
            build_number: room.extra.build_number,
            build_name: room.extra.build_name,
          });
        }
      }
      // changeHouseList = [];
      return result;
    };

    watch(
      () => props.contentTrigger,
      (val) => {
        if (val) {
          handleNextStepClick();
        }
      }
    );

    /**
     * @description: 物业/租赁条款
     */
    const clauseList = ref([]);
    let normalCount = 1;
    // 添加默认的
    const addNormalClause = (item = {}, index) => {
      let currentIndex = index || index == 0 ? index : clauseList.value.length;
      clauseList.value.splice(currentIndex, 0, {
        key: "normal_clause_" + normalCount,
        title: props.content.name,
        ...item,
      });
      normalCount++;
      setClauseChange();
    };

    // 删除
    const handleClauseListRemove = (e) => {
      const { index, type } = e;
      type == "normal" && clauseList.value.splice(index, 1);
      type == "increase" && incrClauseList.value.splice(index, 1);
      type == "discount" && discountClauseList.value.splice(index, 1);
      setClauseChange();
    };
    // 向上||向下添加
    const handleClauseAdd = (e) => {
      const { index, type, way } = e;
      let addIndex = way == "top" ? index : index + 1;
      if (type === "normal") {
        addNormalClause({}, addIndex);
      }
      if (type === "increase") {
        addIncreaseClause({}, addIndex);
      }
      if (type === "discount") {
        addDiscountClause({}, addIndex);
      }
    };
    /**
     * @description: 递增条款
     */
    const incrClauseList = ref([]);
    let incrCount = 1;
    const addIncreaseClause = (item = {}, index) => {
      // if (discountClauseList.value.length) {
      //   message.warning("您添加了优惠条款，系统暂时不支持同时添加递增条款。");
      //   return;
      // }
      let currentIndex =
        index || index == 0 ? index : incrClauseList.value.length;
      incrClauseList.value.splice(currentIndex, 0, {
        key: "increase_clause_" + incrCount,
        ...item,
      });
      incrCount++;
      setClauseChange();
    };
    /**
     * @description: 优惠条款
     */
    const discountClauseList = ref([]);
    let dctCount = 1;
    const addDiscountClause = (item = {}, index) => {
      // if (incrClauseList.value.length) {
      //   message.warning("您添加了递增条款，系统暂时不支持同时添加优惠条款。");
      //   return;
      // }
      let currentIndex =
        index || index == 0 ? index : discountClauseList.value.length;
      discountClauseList.value.splice(currentIndex, 0, {
        key: "discount_clause_" + dctCount,
        ...item,
      });
      dctCount++;
      setClauseChange();
    };

    const bondTypeDisabled = ref(false);
    const isRenewal = computed(
      () =>  $route.query.editType == "renewal"
    );

    const taxRateMap = computed(() => store.getters.taxRateMap);
    const setTaxRateMap = () => {
      store.dispatch("SetTaxRateMap", {
        key: props.content.attribute,
        value: state.formData.tax_clause,
      });
    };
    const getTaxRateMap = (rateObj) => {
      getaxRatelist(rateObj)
    };
    let timer = null;
    watch(
      taxRateMap,
      (rateMap) => {
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        timer = setTimeout(() => {
          if (state.rateDisabled) {
            getTaxRateMap(rateMap[props.content.attribute]);
          }
        }, 300);
      },
      { deep: true }
    );

    // 获取合同租客当前是否绑定发票模板 若存在 获取其税率信息
    const getDefaultTax = (basicInfo) => {
      const { content } = props;
      if (!(basicInfo.owner_id && props.content.cost_type)) return;
      request
        .get("/org", "/contract/ownerDefaultTax", {
          owner_id: basicInfo.owner_id,
          cost_type: props.content.cost_type,
        })
        .then((res) => {
          state.rateList = [];
          if (res.rateList.length) {
            state.rateList = res.rateList.map((item) => ({
              value: utils.toFixed2(item.tax_rate),
            }));
            if (!content.tax_clause) {
              state.formData.tax_clause.taxRate = state.rateList[0].value;
              setTaxRateMap();
            }
          }
        });
    };

    const handleTaxRuleChange = (value) => {
      setTaxRateMap();
    };

    const allHouseList = computed(() => {
      const list =
        JSON.parse(JSON.stringify(store.getters.checkedRoomList)) || [];
      return list.map((item) => {
        item.checked =
          props.content.checkedHouse.findIndex((i) => i.id == item.id) > -1;
        return item;
      });
    });

    // 更新选择的房源信息 解决还是旧数据问题
    watch(
      () => store.getters.checkedRoomList,
      (roomList) => {
        const { content } = props;
        let newList = roomList.filter((item) =>
          state.houseCheckedIds.includes(item.id)
        );
        newList.map((item) => {
          if (!item.inputArea) {
            let data = content.checkedHouse.find((v) => v.id == item.id);
            if (data.inputArea) {
              item.inputArea = data.inputArea;
            }
          }
          return item;
        })
        content.checkedHouse = newList;
        // content.checkedHouse = roomList.filter((item) => {
        //   const current = content.checkedHouse.find((it) => it.id == item.id);
        //   if (current) {
        //     item.rentedArea = current.lease_area || 0; //当前自己占的已租面积
        //     return item;
        //   }
        // });
      }
    );

    let changeHouseList = [];
    const handleCheckHouseChange = (e) => {
      const { content } = props;
      const { type, current, houseList } = e;
      if (type == "check") {
        content.checkedHouse = houseList;
        if (current.checked) {
          store.dispatch("SetPaneCheckedRoom", {
            type: "remove",
            roomIds: current.id,
            clauseId: content.clause_id,
          });
          current.checked = false;
          const idx = content.checkedHouse.findIndex(
            (item) => item.id == current.id
          );
          content.checkedHouse.splice(idx, 1);
        } else {
          store
            .dispatch("GetPaneCheckedRoom", content.clause_id)
            .then((result) => {
              // console.log("------GetPaneCheckedRoom", toRaw(result));
              if (
                result &&
                result.checkedIds &&
                result.checkedIds.length &&
                result.checkedIds.includes(current.id)
              ) {
                // 已被其他pane选择
                message.warning("该房源已被其他条款选中");
                return;
              } else {
                store.dispatch("SetPaneCheckedRoom", {
                  type: "add",
                  roomIds: [current.id],
                  clauseId: content.clause_id,
                });
                current.checked = true;
                content.checkedHouse.push(current);
              }
            });
        }
      } else {
        // 修改面积
        // console.log("-----------让我看看为啥面积不变22", e);
        state.formData.lease_area = e.leaseArea || 0;
        props.content.checkedHouse.map((item) => {
          if (!item.inputArea) {
            let data = houseList.find((v) => v.id == item.id);
            if (data.inputArea) {
              item.inputArea = data.inputArea;
            }
          }
        });
        changeHouseList = houseList;
      }
    };

    const getLeaseArea = () => {
      state.formData.lease_area = 0;
      props.content.checkedHouse.forEach((room) => {
        if (room.inputArea && room.inputArea[props.content.attribute]) {
          state.formData.lease_area =
            Number(state.formData.lease_area) +
            Number(room.inputArea[props.content.attribute] || 0);
        }
      });
    };

    watch(
      () => store.getters.addFormData.basicInfo,
      (basicInfo) => {
        if (
          !isCostContract.value &&
          basicInfo &&
          basicInfo.owner_id &&
          props.content.cost_type
        ) {
          getDefaultTax(basicInfo);
          getaxRatelist();
        }
      }
    );

    const init = () => {
      // console.log("contentcontentcontentcontent111", toRaw(props.content));
      const { content } = props;
      let useLocal = false;
      if (content.contentInfo) {
        useLocal = true;
        for (let key in content.contentInfo) {
          state.formData[key] = content.contentInfo[key];
        }
      }
      if (content.bond_clause && !useLocal) {
        state.formData.bond_clause = {
          ...content.bond_clause,
        };
      }
      if (content.checkedHouse && content.checkedHouse.length) {
        state.houseCheckedIds = content.checkedHouse.map((item) => item.id);
        getLeaseArea();
      }
      state.rateDisabled = false;
      let tax_clause = content.tax_clause || content?.contentInfo?.tax_clause;
      if (tax_clause) {
        getTaxRateMap(tax_clause);
        if (content.key.indexOf("default") > -1) {
          setTaxRateMap();
        }
      } else {
        const taxRate = taxRateMap.value[content.attribute];
        if (taxRate) {
          state.rateDisabled = true;
          getTaxRateMap(taxRate);
        }
      }
      if (content.basic_clause && !useLocal) {
        state.formData.lease_area = utils.parseNumber(
          content.basic_clause.lease_area,
          4
        );
      }
      // 物业条款可以填0
      state.rulesData.lease_area =
        content.attribute == "property" ? numberRule2 : numberRule;
      if (content.remark_clause && !useLocal) {
        state.formData.remark_clause = content.remark_clause;
      }
      if (content.bond_type) {
        if (!useLocal) {
          state.formData.bond_clause.bond_type = content.bond_type;
        }
        bondTypeDisabled.value = true;
      }

      if (!content.use_bond) {
        // 不需要保证金的条款 保证金条款类型不必填 金额置为0且不显示保证金条款
        delete state.rulesData["bond_clause.bond_type"];
        if (!useLocal) {
          state.formData.bond_clause.bond_type = undefined;
          state.formData.bond_clause.bond_price = 0;
        }
      }

      // 当成本合同，保证金类型默认是成本物业保证金
      if (isCostContract.value) {
        if (content.cost_type && content.cost_type == "cost_16") {
          // 是物业条款时，
          state.formData.bond_clause.bond_type = "bond_6";
          bondTypeDisabled.value = true;
          content.bond_type_txt = "成本物业费保证金";
        } else {
          state.formData.bond_clause.bond_type = "bond_5";
          bondTypeDisabled.value = true;
          content.bond_type_txt = "成本租金保证金";
        }
      }
      if (!content.use_lease) {
        delete state.rulesData["tax_clause.taxRate"];
      }
      if (content.multiple_clause && content.multiple_clause.length) {
        // console.log("初始化multiple_clause");
        content.multiple_clause.forEach((item) => {
          addNormalClause(item);
        });
      } else if (content.attribute == "other" && !content.cost_type) {
        // 如果选择的是自定义的“其他条款”并且未勾选“租期条款”时
        // console.log("选择的是自定义的“其他条款”并且未勾选“租期条款”");
      } else {
        // 判断是否开启	保证金条款
        if (content.useBond != 1) {
          //   默认物业费条款
          clauseList.value.push({
            key: "pc_default",
            title: content.name,
          });
        }
      }
      if (content.increment_clause && content.increment_clause.length) {
        content.increment_clause.forEach((item) => {
          addIncreaseClause(item);
        });
      }
      if (content.discount_clause && content.discount_clause.length) {
        content.discount_clause.forEach((item) => {
          addDiscountClause(item);
        });
      }
      if (!isRenewal.value && content.report_detail) {
        // 变更合同时需要手动生成明细
        if (!isChangeContract.value && !isPurposeChangeContract.value) {
          leaseDetail.value = utils.getClauseDetailByGroup(
            content.report_detail,
            content.attribute
          );
          nextTick(() => {
            setClauseChange(false);
          });
        }
      }

      store.dispatch("ContractInit").then((res) => {
        state.optionData = res;
        if (!state.areaUnit) {
          state.areaUnit =
            res.lease_square_unit && res.lease_square_unit.length
              ? res.lease_square_unit[0]
              : {};
        }
        if (!state.formData.bond_clause.bond_unit) {
          state.formData.bond_clause.bond_unit =
            res.bond_unit && res.bond_unit.length
              ? res.bond_unit[0].key
              : undefined;
        }
        if (!state.formData.bond_clause.currencyUnit) {
          state.formData.bond_clause.currencyUnit =
            res.currencyUnit && res.currencyUnit.length
              ? res.currencyUnit[0].key
              : undefined;
        }

        // 成本合同
        if (isCostContract.value) {
          if (res.cost_lease_unit && res.cost_lease_unit.length > 2) {
            let list1 = JSON.parse(JSON.stringify(res.cost_lease_unit));
            let list2 = JSON.parse(JSON.stringify(res.cost_lease_unit));
            if (content.cost_type && content.cost_type == "cost_16") {
              // 如果是物业条款，固定物业费 + 托管计租
              list1[0] = list1[2];
              list1.pop();
              state.lease_mode_List = list1;
              state.formData.lease_mode = list1[0].key;
            } else {
              // 默认展示固定租金+托管计租
              list2.pop();
              state.lease_mode_List = list2;
              state.formData.lease_mode = list2[0].key;
            }
            // console.log(state.formData.lease_mode, state.lease_mode_List);
          }
        }
      });

      if (
        (content.use_lease && !isCostContract.value) ||
        (content.useLease == 1 && content.useBond == 1) ||
        content.useBond == 0 ||
        content.useLease == 1
      ) {
        getaxRatelist();
      }
    };

    const getaxRatelist = (rateObj) => {
      if (!props?.content?.checkedHouse[0]) {
        return;
      }
      let extra = props.content.checkedHouse[0].extra;
      request
        .get("/org", "/contract/tax_rule", {
          build_id: extra.build_id,
          cost_type: props.content.cost_type,
        })
        .then((res) => {
          state.taxRatelist = [];
          if (res.list.length > 0) {
            for (let i = 0; i < res.list.length; i++) {
              state.taxRatelist.push({
                value: Number((`${res.list[i].template_id}` + res.list[i].tax_code_id)),
                label:
                  res.list[i].tax_rate + `   （${res.list[i].template_name}）`,
                tax_rate: res.list[i].tax_rate,
              });
            }
            let number = 0
            if(rateObj){
              for (let i = 0; i < state.taxRatelist.length; i++) {
                if(state.taxRatelist[i].value == rateObj.taxRate_id && state.taxRatelist[i].tax_rate == rateObj.taxRate){
                  number++
                }
              }
            }
            if(number){
              state.formData.tax_clause.taxRate = Number(rateObj.taxRate);
              state.formData.tax_clause.taxRule = Number(rateObj.taxRule);
              state.formData.tax_clause.taxRate_id = Number(rateObj.taxRate_id);
            }else {
              if(!state.formData.tax_clause.taxRate_id || !state.formData.tax_clause.taxRate){
                state.formData.tax_clause.taxRate_id = state.taxRatelist[0].value;
                state.formData.tax_clause.taxRate = state.taxRatelist[0].tax_rate;
              }
              if (rateObj?.taxRule) {
                state.formData.tax_clause.taxRule = Number(rateObj.taxRule);
              }
            }
          }else {
            if(rateObj){
              state.formData.tax_clause.taxRate = Number(rateObj.taxRate);
              state.formData.tax_clause.taxRule = Number(rateObj.taxRule);
            }
          }
        });
    };

    const changetaxRate = (value) => {
      for (let i = 0; i < state.taxRatelist.length; i++) {
        if (state.taxRatelist[i].value == value) {
          state.formData.tax_clause.taxRate = state.taxRatelist[i].tax_rate;
        }
      }
    };

    const bondUnitDisabled = ref(false);
    let bondUnitFlag = {};
    const handleClauseChange = (e) => {
      if (e.compute_lease) {
        bondUnitDisabled.value = false;
        state.formData.bond_clause.bond_unit =
          state.formData.bond_clause.bond_unit || "unit_1";
        bondUnitFlag[e.key] = e.compute_lease;
        for (let key in bondUnitFlag) {
          if (bondUnitFlag[key] != "unit1") {
            state.formData.bond_clause.bond_unit = "unit_2";
            bondUnitDisabled.value = true;
            return;
          }
        }
      }
    };

    const paymentByRooms = computed(() => {
      return store.getters.orgInfo.paymentByRooms;
    });

    init();

    let stateData = toRefs(state);

    // 是否意向合同 或者意向合同变更
    const isPurposeContract = computed(
      () => $route.query.contractType == "purposeContract" || $route.query.contractType == "purposeContractChange"
    );

    const getBuildBindByRoomInfo = (roomInfo) => {
      return {
        village: {
          id: roomInfo.extra.village_id,
          name: roomInfo.extra.village_name,
          short_name: roomInfo.extra.village_short_name,
        },
        build: {
          id: roomInfo.extra.build_id,
          build_name: roomInfo.extra.build_name,
          build_number: roomInfo.extra.build_number,
        },
        room: [
          {
            id: roomInfo.id,
            build_id: roomInfo.extra.build_id,
            layer_id: roomInfo.extra.layer_id,
            room_name: roomInfo.room_name,
            layer_name: roomInfo.extra.layer_name,
            room_number: roomInfo.room_number,
            layer_number: roomInfo.extra.layer_number,
          },
        ],
      };
    };

    watch(
      [
        () => clauseList.value,
        () => incrClauseList.value,
        () => discountClauseList.value,
      ],
      (
        [defaultClause, roomList, multiBuild],
        [preClause, preRoomList, preMultiBuild]
      ) => {
        setDraftLocal();
      },
      { deep: true }
    );

    const draftDataChange = (source, target, type) => {
      if (source.content) {
        for (let key in source.content) {
          target[key] = source.content[key];
        }
      }
    };

    return {
      ...stateData,
      validateInfos,
      bondTypeDisabled,
      clauseList,
      incrClauseList,
      discountClauseList,
      paneFrom,
      trigger,
      bondUnitDisabled,
      leaseDetail,
      genLoading,
      detailParams,
      submitType,
      handleAreaChange,
      addNormalClause,
      handleClauseListRemove,
      addIncreaseClause,
      addDiscountClause,
      getLeaseDetail,
      handleValidateSuccess,
      handleValidateFail,
      handleClauseChange,
      handleTaxRuleChange,
      isCostContract,
      handleCostLeaseChange,
      handleCheckHouseChange,
      allHouseList,
      includeSelfArea,
      paymentByRooms,
      isPurposeContract,
      canAddNormalClause,
      handleClauseAdd,
      canAddIncreaseClause,
      canAddDiscountClause,
      changetaxRate,
      getaxRatelist,
      draftDataChange,
    };
  },
});
</script>

<style lang="less" scoped>
.fee-clause {
  .btn-row {
    height: 40px;
    border: 1px solid #f4f4f4;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .detail {
    height: 50px;
    border: 1px solid @primary-color;
    margin-top: 40px;
  }
}
</style>
